package servlet;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Calendar;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import decoder.ChineseDecoder;

import model.Goods;
import model.Member;
import model.MemberDiscount;
import model.Record;
import model.Saler;
import factory.DaoFactory;

/**
 * Servlet implementation class SaleMessageServlet
 */
@WebServlet("/SaleMessageServlet")
public class SaleMessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SaleMessageServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		int id = Integer.parseInt(request.getParameter("id"));
		Date date = new Date(Calendar.getInstance().getTimeInMillis());
		Goods goods = DaoFactory.getGoodsDao().find(id, date);
		request.setAttribute("goods", goods);
		String address ="/jsp/SaleMessage.jsp?name=" + name;
		RequestDispatcher dispatcher =request.getRequestDispatcher(address);
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("name"));
		int id = Integer.parseInt(request.getParameter("id"));
		Date date = new Date(Calendar.getInstance().getTimeInMillis());
		String memberName = ChineseDecoder.getUtf8FromIso8859_1(request.getParameter("member"));
		int quantity = 0;
		
		try {
			quantity = Integer.parseInt(request.getParameter("num"));
		} catch(NumberFormatException e) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SaleQuantityError&name=" + name + "&id=" + id);
			return;
		}
		
		Goods goods = DaoFactory.getGoodsDao().find(id, date);

		if (quantity > goods.getQuantity()) {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SaleTooMuchError&name=" + name + "&id=" + id);
			return;
		}
		
		Timestamp time = new Timestamp(Calendar.getInstance().getTimeInMillis());
		Saler saler = DaoFactory.getSalerDao().find(name);
		Member member = DaoFactory.getMemberDao().find(memberName);
		member.setTotalConsumption(member.getTotalConsumption() + quantity*goods.getPrice());
		MemberDiscount discount = DaoFactory.getDiscountDao().findHighest(member.getTotalConsumption());
		if (discount != null) {
			goods.setPrice(goods.getPrice()*discount.getDiscount());
		}
		Record record = new Record(saler.getShop(), memberName, time, id, goods.getName(), quantity, quantity*goods.getPrice());

		goods.setQuantity(goods.getQuantity() - quantity);
		boolean success = DaoFactory.getRecordDao().save(record) && DaoFactory.getGoodsDao().updateQuantityByIdDate(goods) && DaoFactory.getMemberDao().updateConsumptionByName(member);
		
		if (success) {
			response.sendRedirect(request.getContextPath() + "/SaleGoodsServlet?name=" + name);
		} else {
			response.sendRedirect(request.getContextPath() + "/jsp/ErrorPage.jsp?error=SaleDatabaseError&name=" + name + "&id=" + id);
		}
		
	}

}
